package com.LachesismStorm.lachesism.member.util;

import com.LachesismStorm.lachesism.core.common.enums.ResponseCodeEnum;
import com.LachesismStorm.lachesism.core.exception.Asserts;
import com.LachesismStorm.lachesism.member.vo.MemberDetails;
import com.LachesismStorm.lachesism.member.vo.UmsMember;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 用户操作
 *
 * @author: juiet
 * @date: 2022年06月16日 0:37
 */
public class MemberUtil {
    public static UmsMember getUserInfo(){
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || !auth.isAuthenticated()) {
            Asserts.fail(ResponseCodeEnum.UNAUTHORIZED);
        }

        boolean result = auth.getPrincipal() instanceof MemberDetails;
        if(!result){
            Asserts.fail(ResponseCodeEnum.UNAUTHORIZED);
        }

        MemberDetails userDetails = (MemberDetails) auth.getPrincipal();
        return userDetails.getUmsMember();
    }

    public static Integer getUserId() {
        return getUserInfo().getId();
    }

    public static String getMemberPhone() {
        String phone = "";
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || !auth.isAuthenticated()) {
            return phone;
        }
        boolean result = auth.getPrincipal() instanceof MemberDetails;
        if (!result) {
            return phone;
        }
        MemberDetails userDetails = (MemberDetails) auth.getPrincipal();
        phone = userDetails.getUmsMember().getPhone();
        return phone;
    }
}
